package com.tqfframe.website.web.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tqfframe.website.util.DateUtil;
import com.tqfframe.website.util.HttpClient;
import com.tqfframe.website.web.common.Result;
import com.tqfframe.website.web.common.StockCalculate;
import com.tqfframe.website.web.controller.StockController;
import com.tqfframe.website.web.dao.StockInfoMapper;
import com.tqfframe.website.web.dao.StockMapper;
import com.tqfframe.website.web.entry.StockEntity;
import com.tqfframe.website.web.entry.StockInfoEntity;
import com.tqfframe.website.web.entry.TestEntity;
import com.tqfframe.website.web.service.StockService;
import com.tqfframe.website.web.vo.StockDTO;
import com.tqfframe.website.web.vo.StockInfoDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Tang-QiFeng on 2021/1/2
 */
@Service
public class StockServiceImpl implements StockService {

    Logger logger = LoggerFactory.getLogger(StockServiceImpl.class);

    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private StockInfoMapper stockInfoMapper;

    private final static String url="http://money.finance.sina.com.cn/quotes_service/api/json_v2.php/CN_MarketData.getKLineData";
    private final static String url2="http://hq.sinajs.cn/list";

    @Override
    public List<StockInfoDTO> getTodtayData() {
        IPage<StockInfoDTO> iPageStock=stockInfoMapper.getResult(new Page(0,1000));
        List<StockInfoDTO> listStock=iPageStock.getRecords();
        return listStock;
    }


    @Override
    public List getKValueById(String id) {
        IPage<StockDTO> iPageStock=stockMapper.getPageByNodes(new Page(0,100),id);
        List<StockDTO> listStock=iPageStock.getRecords();
        return listStock;
    }

    @Override
    public Result executeK() {
        Result result = new Result();
       Map<String, Object> map = new HashMap<>();
//        List<StockInfoEntity> list=stockInfoMapper.selectByMap(map);
        IPage<StockInfoDTO> listInfo=stockInfoMapper.getResultNo(new Page(0,1000));
        List<StockInfoDTO> list=listInfo.getRecords();
        int z=list.size();
        logger.info("总共"+z);
//        for(StockInfoEntity stockInfoEntity:list){
        for(StockInfoDTO stockInfoEntity:list){
            String no=stockInfoEntity.getStockNo();
            logger.info(no+"执行k值计算。。。还剩:"+z--);
            IPage<StockDTO> iPageStock=stockMapper.getPageByNo(new Page(0,1),no);
            List<StockDTO> listStock=iPageStock.getRecords();
            Double kvalue=listStock.get(0).getKValue();         //昨天的k值
            //读取接口的数据
//            JSONArray jsonArray = getListData(no,10);      //十日数据
            JSONArray jsonArray = getListData(no,9);      //九日数据
            if(jsonArray!=null && jsonArray.size()>0){
//                jsonArray.remove(9);
                Map<String,String> newMap= (Map) jsonArray.get(jsonArray.size()-1);
                Double highMax=Double.valueOf(newMap.get("high"));  //九日最高价
                Double lowMin=Double.valueOf(newMap.get("low"));    //九日最低价
                for(Object jsonObject: jsonArray){
                    Map<String,String> mapInfo=(Map) jsonObject;
                    if(Double.valueOf(mapInfo.get("high"))>highMax){
                        highMax=Double.valueOf(mapInfo.get("high"));
                    }
                    if(Double.valueOf(mapInfo.get("low"))<lowMin){
                        lowMin=Double.valueOf(mapInfo.get("low"));
                    }
                }

                if(map!=null){
                    String day=newMap.get("day");
                    Double open=Double.valueOf(newMap.get("open"));        //开盘价
                    Double high=Double.valueOf(newMap.get("high"));        //最高价
                    Double low=Double.valueOf(newMap.get("low"));          //最低价
                    Double close=Double.valueOf(newMap.get("close"));      //收盘价
                    String volume=newMap.get("volume");    //交易量
                    Double newKValue=StockCalculate.getKvalue( open, lowMin, close, highMax, Double.valueOf(kvalue));
                    StockEntity stockEntity=new StockEntity();
                    stockEntity.setStockNo(no);
                    stockEntity.setDayTime(DateUtil.StringToDate(day));
                    stockEntity.setClose(close);
                    stockEntity.setHigh(high);
                    stockEntity.setLow(low);
                    stockEntity.setOpen(open);
                    stockEntity.setVolume(volume);
                    stockEntity.setKValue(newKValue);
                    int aa = stockMapper.insert(stockEntity);
                    if (aa==0) {
                        logger.error(no+"插入失败");
                    }else{
                        StockInfoEntity upDataStockInfoEntity=new StockInfoEntity();
                        //0跌 1涨
                        if(newKValue>kvalue){
                            upDataStockInfoEntity.setUpdown(1);
                        }else{
                            upDataStockInfoEntity.setUpdown(0);
                        }
                        upDataStockInfoEntity.setId(stockInfoEntity.getId());
                        upDataStockInfoEntity.setUpdate_time(new Date());
                        upDataStockInfoEntity.setKValue(newKValue);
                        upDataStockInfoEntity.setTop(stockInfoEntity.getTop());
                        stockInfoMapper.updateById(upDataStockInfoEntity);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public Result insertStock(String no,String k_value) {
        Result result = new Result();
        Map<String, Object> oldMap = new HashMap<>();
        oldMap.put("stock_no",no);
        List<StockInfoEntity> list=stockInfoMapper.selectByMap(oldMap);
        if(list.size()==0){
            Map<String,String> map= getData(no);
            if(map!=null){
                String day=map.get("day");
                Double open=Double.valueOf(map.get("open"));        //开盘价
                Double high=Double.valueOf(map.get("high"));        //最高价
                Double low=Double.valueOf(map.get("low"));          //最低价
                Double close=Double.valueOf(map.get("close"));      //收盘价
                String volume=map.get("volume");    //交易量
                String name=map.get("name");    //股票名字
                StockEntity stockEntity=new StockEntity();
                stockEntity.setStockNo(no);
                stockEntity.setDayTime(DateUtil.StringToDate(day));
                stockEntity.setClose(close);
                stockEntity.setHigh(high);
                stockEntity.setLow(low);
                stockEntity.setOpen(open);
                stockEntity.setVolume(volume);
                stockEntity.setKValue(Double.valueOf(k_value));
                int aa = stockMapper.insert(stockEntity);
                if (aa==0) {
                    result.setSuccess(false);
                    result.setMessage("添加入库错误");
                } else {
                    StockInfoEntity stockInfoEntity=new StockInfoEntity();
                    stockInfoEntity.setStockName(name);
                    stockInfoEntity.setStockNo(no);
                    stockInfoEntity.setKValue(Double.valueOf(k_value));
                    stockInfoMapper.insert(stockInfoEntity);
                    result.setSuccess(true);
                }
            }else{
                result.setSuccess(false);
                result.setMessage("股票代码错误");
            }
        }else{
            result.setSuccess(false);
            result.setMessage("已存在");
        }
        return result;
    }

    @Override
    public Result updateStock(String id, String value) {
        Result result = new Result();
        StockInfoEntity info=stockInfoMapper.selectById(id);
        StockInfoEntity stockInfoEntity=new StockInfoEntity();
        stockInfoEntity.setId(Integer.valueOf(id));
        stockInfoEntity.setUpdate_time(new Date());
        stockInfoEntity.setKValue(info.getKValue());
        stockInfoEntity.setTop(Integer.valueOf(value));
        stockInfoEntity.setUpdown(info.getUpdown());
        stockInfoMapper.updateById(stockInfoEntity);
        result.setMessage("修改成功");
        return result;
    }

    @Override
    public Integer getExcuteNum() {
        IPage<StockInfoDTO> listInfo=stockInfoMapper.getResultNo(new Page(0,1000));
        return  listInfo.getRecords().size();
    }

    public  JSONArray  getListData(String no,int num) {
        try {
            //防止刷太快被封禁。
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String result = HttpClient.doGet(url+"?symbol="+no+"&scale=240&ma=no&datalen="+num);
        JSONArray jsonArray =null;
        try{
            jsonArray = JSONArray.parseArray(result);
        }catch (Exception ex){
           logger.error(no+"出错啦");
        }
        return jsonArray;
    }

    public  Map<String,String> getData(String no) {
        Map<String,String> map=new HashMap<>();
        try{
            String result = HttpClient.doGet(url2+"="+no);
            result=result.replaceAll("var hq_str_"+no+"=\"","");
            result=result.replaceAll("\";","");
            String values[]=result.split(",");
            map.put("name",values[0]);
            map.put("open",values[1]);
            map.put("close",values[3]);
            map.put("high",values[4]);
            map.put("low",values[5]);
            map.put("volume",values[8]);
            map.put("day",values[30]);
//        for(int i=0;i<values.length;i++){
////            System.out.println(i +"  :   " +values[i]);
////        }
        }catch (Exception ex){
            return null;
        }
        return map;
    }


    public static void main(String[] args) {
        new StockServiceImpl().getData("sh601688");
    }

}
